package com.bbm.communitysystem.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bbm.communitysystem.core.domain.R;
import com.bbm.communitysystem.domain.News;
import com.bbm.communitysystem.domain.bo.NewsBo;
import com.bbm.communitysystem.domain.dto.NewsDto;
import com.bbm.communitysystem.domain.vo.HomeNewsPageVo;
import com.bbm.communitysystem.domain.vo.PageVo;
import com.bbm.communitysystem.service.impl.NewsServiceImpl;
import com.bbm.communitysystem.tools.DemoDate;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bbm
 * @since 2025-02-13
 */
@Tag(name = "新闻")
@RestController
@RequestMapping("/news")
@RequiredArgsConstructor
public class NewsController {

    private final NewsServiceImpl newsService;


    /**
     * 首页获取新闻列表
     * @param page
     * @param size
     * @return
     */
    @Operation(summary = "首页获取新闻列表")
    @GetMapping()
    @Parameters({
            @Parameter(description = "页数", name = "page"),
            @Parameter(description = "每页数量", name = "size")
    })
    public R<PageVo<HomeNewsPageVo>> getNewsList(@RequestParam("page") Integer page, @RequestParam("size") Integer size) {

        Page<News> newsPage = new Page<>(page, size);

        LambdaQueryWrapper<News> newsLambdaQueryWrapper = new LambdaQueryWrapper<>();

        newsLambdaQueryWrapper.eq(News::getStatus, 2);
        newsLambdaQueryWrapper.orderByDesc(News::getUpdateTime);

        Page<News> page1 = newsService.page(newsPage, newsLambdaQueryWrapper);



        PageVo<HomeNewsPageVo> pageVo = new PageVo<>(page1);

        page1.getRecords().forEach(item -> {
            HomeNewsPageVo homeNewsPageVo = new HomeNewsPageVo();
            homeNewsPageVo.setNewsPublicTime(item.getNewsTime());
            homeNewsPageVo.setNewsTitle(item.getNewsTitle());
            homeNewsPageVo.setNewsId(item.getId());
            homeNewsPageVo.setNewsImg(item.getNewsImg());

            pageVo.getRecords().add(homeNewsPageVo);
        });

        return R.ok(pageVo);
    }


    @Operation(summary = "新增新闻")
    @Parameters({
            @Parameter(description = "新闻标题", name = "title"),
            @Parameter(description = "新闻内容", name = "content"),
            @Parameter(description = "更新人", name = "update")
    })
    @PostMapping("/add")
    public R<String> addNews(@RequestParam("img")MultipartFile img, @RequestParam("title") String title,
                     @RequestParam("content") String content, @RequestParam("update") String userId) {

        NewsBo newsBo = new NewsBo();

        newsBo.setNewsImg(img);
        newsBo.setUpdateBy(userId);
        newsBo.setNewsContent(content);
        newsBo.setNewsTitle(title);

        NewsDto news = newsService.createNews(newsBo);

        if (news == null) {
            return R.error("新增失败");
        }

        return R.ok("新增成功");
    }

    @Operation(summary = "删除新闻")
    @DeleteMapping("/{id}")
    @Parameter(description = "新闻id", name = "id")
    public R delNews(@PathVariable("id") Integer id) {
        NewsBo newsBo = new NewsBo();
        newsBo.setId(id);

        NewsDto newsDto = newsService.delNewsImg(newsBo);

        if (newsDto == null) {
            return R.error("删除失败");
        }


        return R.ok("删除成功");
    }

    @Operation(summary = "修改新闻")
    @PutMapping("")
    public R putNews(@RequestBody NewsDto newsDto) {
        boolean update;

        if (newsDto.getStatus() == 2) {
            News one = newsService.lambdaQuery()
                    .eq(News::getId, newsDto.getId())
                    .one();

            if (one == null) {
                return R.error("修改失败, NOT FUND");
            }

            update = newsService.lambdaUpdate().eq(News::getId, newsDto.getId())
                    .set(!newsDto.getNewsContent().isEmpty(), News::getNewsContent, newsDto.getNewsContent())
                    .set(!newsDto.getNewsTitle().isEmpty(), News::getNewsTitle, newsDto.getNewsTitle())
                    .set(News::getUpdateBy,newsDto.getUpdateBy())
                    .set(one.getStatus() != 2 ,News::getNewsTime, DemoDate.getNow())
                    .set(News::getUpdateTime, System.currentTimeMillis() + "")
                    .set(News::getStatus, newsDto.getStatus())
                    .update();

        } else {
            update = newsService.lambdaUpdate().eq(News::getId, newsDto.getId())
                    .set(!newsDto.getNewsContent().isEmpty(), News::getNewsContent, newsDto.getNewsContent())
                    .set(!newsDto.getNewsTitle().isEmpty(), News::getNewsTitle, newsDto.getNewsTitle())
                    .set(News::getUpdateBy,newsDto.getUpdateBy())
                    .set(News::getUpdateTime, System.currentTimeMillis() + "")
                    .set(News::getStatus, newsDto.getStatus())
                    .update();

            if (!update) {
                return R.error("修改失败");
            }
        }

        return R.ok("修改成功");
    }

    @Operation(summary = "修改新闻图片")
    @PutMapping("/put/img")
    @Parameters({
            @Parameter(description = "图片", name = "img"),
            @Parameter(description = "新闻id", name = "newsId"),
            @Parameter(description = "用户id", name = "user")
    })
    public R putNewsImg(@RequestParam("img") MultipartFile img, @RequestParam("newsId") Integer newsId,
                       @RequestParam("user") Integer user) {

        NewsBo newsBo = new NewsBo();
        newsBo.setNewsImg(img);
        newsBo.setId(newsId);
        newsBo.setUpdateBy(user + "");
        NewsDto newsDto = newsService.putNewsImg(newsBo);

        if (newsDto == null) {
            return R.error("修改失败");
        }

        return R.ok("修改成功");
    }

    @Operation(summary = "获取新闻列表, dev环境")
    @GetMapping("/dev")
    public R getNewsList() {
        return R.ok(newsService.list());
    }



    @Operation(summary = "获取新闻详情")
    @GetMapping("/getNewsDe/{id}")
    public R getNewsDe(@PathVariable("id") Integer id) {
        News News = newsService.getById(id);

        return R.ok(News);
    }


}


